/*
 * All rights Reserved, Designed By cloudland Copyright(C) 2010-2014
 *
 * fileName:  Securitys.java
 * author:  lei
 * Company:  Cloudland Studio
 * Createdate:  2013-9-14 上午10:01:44
 *   
 * Modification  History:
 *     Date           Author        Version        
 * -------------------------------------------
 * 2013-9-14          Lei            1.0        
 *
 * Why & What is modified:
 * 1.0: 文件创建
 */
package org.cloudland.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

 /**
 * <pre> 
 * 加密提供工具类
 * 提供MD5、Base64等加密方式。以及压缩功能。
 * </pre>
 * @ClassName  Securitys
 * @author  lei
 * @version  %I%, %G%
 * @see  
 * @since   JDK1.6
 *
 */
public class Securitys {

	/**
     * MD5_HEX_DIGITS MD5加密时，用来将字节转换成16进制表示的字符。
     */
    private static char[] MD5_HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    
    /** 
     * 将字符串进行MD5加密处理。<br>
     *
     * @param text 字符串
     * @return MD5加密后字符串 
     */
    public static String doMD5(final String text) {
        byte[] source = text.getBytes();
        
        MessageDigest md = null;
        try
        {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        
        md.update(source);
        byte[] temp = md.digest(); // MD5 的计算结果是一个 128位的长整数，用字节表示为 16个字节
        
        char[] result = new char[2 * temp.length];
        for (int i = 0, k = 0; i < temp.length; i++)
        {
            byte b = temp[i];
            result[k++] = MD5_HEX_DIGITS[b >>> 4 & 0xf];
            result[k++] = MD5_HEX_DIGITS[b & 0xf];
        }
        
        return new String(result);
    }
    
    /** 
     * 使用Base64对字符串加密，并将结果返回。<br>
     *
     * @param text 字符串
     * @return base64加密后字符串
     */
    public static String doBase64Encode(String text) {
        return doBase64Encode(text, null);
    }
    
    /** 
     * 使用Base64对字符串加密，并将结果返回。<br>
     *
     * @param text 字符串
     * @param charset 字符编码
     * @return base64加密后字符串
     */
    public static String doBase64Encode(String text, String charset) {
        
        if (null == charset || charset.length() <= 0) {
            charset = "UTF-8";
        }
        
        byte[] b = null;
        try
        {
            b = text.getBytes(charset);
        }
        catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return Base64.encode(b);
    }
    
    /** 
     * 使用Base64对字符串解密，并返回结果。<br>
     *
     * @param text 字符串
     * @return Base64解密后的结果
     */
    public static String doBase64Decode(String text)
    {
        return doBase64Decode(text, null);
    }
    
    /** 
     * 使用Base64对字符串解密，并返回结果。<br>
     *
     * @param text 字符串
     * @param charset 字符编码
     * @return Base64解密后的结果
     */
    public static String doBase64Decode(String text, String charset) {
        
        if (null == charset || charset.length() <= 0) {
            charset = "UTF-8";
        }
        
        byte[] b = Base64.decode(text);

        String result = null;
        try
        {
            result = new String(b, charset);
        }
        catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return result;
    }
    
    /** 
     * 对字符串进行压缩。<br>
     * <pre>
     * 对带有可能产生歧义标签的字符串进行压缩处理。如：HTML字符粗
     * </pre>
     *
     * @param text 字符串
     * @return 压缩后的字符串
     */
    public static String doCompress(final String text) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream objOut = null;
        try
        {
            objOut = new ObjectOutputStream(new GZIPOutputStream(bos));
            objOut.writeObject(text);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        } finally {
            if (null != objOut) {
                try
                {
                    objOut.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        
        byte[] tempByte = bos.toByteArray();
        return Base64.encode(tempByte);
    }
    
    
    /** 
     * 对字符串进行解缩。<br>
     *
     * @param text 压缩的字符串
     * @return 解压后的源文字符串
     */
    public static String doDecompress(final String text){
        try{
            if (text == null || text.trim().length() <= 0)
                return text;
            for (int i = 0; i < text.length(); i++)
            {
                if (text.substring(i, i + 1).equalsIgnoreCase(">"))
                {
                    return text;
                }
            }
            byte[] tempByte = Base64.decode(text);
            ByteArrayInputStream bos = new ByteArrayInputStream(tempByte);
            ObjectInputStream objIn = new ObjectInputStream(new GZIPInputStream(bos));
            Object obj = objIn.readObject();
            return (String) obj;
        }catch(Exception e){
            return text;
        }
    }
    
    
}


/**
 * Base64 加密算法
 * @ClassName Base64
 * @Description 
 * @author zhuzhonglei
 * @date 2013-6-19 下午5:34:08
 * @version 1.0
 *
 */
class Base64
{
    private static final char[] S_BASE64CHAR = {'A', 'B', 'C', 'D', 'E', 'F',
            'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
            'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', '+', '/'};
    
    private static final char S_BASE64PAD = '=';
    
    private static final byte[] S_DECODETABLE = new byte[128];
    static
    {
        for (int i = 0; i < S_DECODETABLE.length; i++)
            S_DECODETABLE[i] = Byte.MAX_VALUE; // 127
        for (int i = 0; i < S_BASE64CHAR.length; i++)
            // 0 to 63
            S_DECODETABLE[S_BASE64CHAR[i]] = (byte) i;
    }
    
    private static int decode0(char[] ibuf, byte[] obuf, int wp)
    {
        int outlen = 3;
        if (ibuf[3] == S_BASE64PAD)
            outlen = 2;
        if (ibuf[2] == S_BASE64PAD)
            outlen = 1;
        int b0 = S_DECODETABLE[ibuf[0]];
        int b1 = S_DECODETABLE[ibuf[1]];
        int b2 = S_DECODETABLE[ibuf[2]];
        int b3 = S_DECODETABLE[ibuf[3]];
        switch (outlen)
        {
            case 1:
                obuf[wp] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3);
                return 1;
            case 2:
                obuf[wp++] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3);
                obuf[wp] = (byte) (b1 << 4 & 0xf0 | b2 >> 2 & 0xf);
                return 2;
            case 3:
                obuf[wp++] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3);
                obuf[wp++] = (byte) (b1 << 4 & 0xf0 | b2 >> 2 & 0xf);
                obuf[wp] = (byte) (b2 << 6 & 0xc0 | b3 & 0x3f);
                return 3;
            default:
                throw new RuntimeException("Internal Errror");
        }
    }
    
    /**
     * Decode the base64 data.
     * @param data The base64 encoded data to be decoded
     * @param off The offset within the encoded data at which to start decoding
     * @param len The length of data to decode
     * @return The decoded data
     */
    public static byte[] decode(char[] data, int off, int len)
    {
        char[] ibuf = new char[4];
        int ibufcount = 0;
        byte[] obuf = new byte[len / 4 * 3 + 3];
        int obufcount = 0;
        for (int i = off; i < off + len; i++)
        {
            char ch = data[i];
            if (ch == S_BASE64PAD || ch < S_DECODETABLE.length
                    && S_DECODETABLE[ch] != Byte.MAX_VALUE)
            {
                ibuf[ibufcount++] = ch;
                if (ibufcount == ibuf.length)
                {
                    ibufcount = 0;
                    obufcount += decode0(ibuf, obuf, obufcount);
                }
            }
        }
        if (obufcount == obuf.length)
            return obuf;
        byte[] ret = new byte[obufcount];
        System.arraycopy(obuf, 0, ret, 0, obufcount);
        return ret;
    }
    
    /**
     * Decode the base64 data.
     * @param data The base64 encoded data to be decoded
     * @return The decoded data
     */
    public static byte[] decode(String data)
    {
        char[] ibuf = new char[4];
        int ibufcount = 0;
        byte[] obuf = new byte[data.length() / 4 * 3 + 3];
        int obufcount = 0;
        for (int i = 0; i < data.length(); i++)
        {
            char ch = data.charAt(i);
            if (ch == S_BASE64PAD || ch < S_DECODETABLE.length
                    && S_DECODETABLE[ch] != Byte.MAX_VALUE)
            {
                ibuf[ibufcount++] = ch;
                if (ibufcount == ibuf.length)
                {
                    ibufcount = 0;
                    obufcount += decode0(ibuf, obuf, obufcount);
                }
            }
        }
        if (obufcount == obuf.length)
            return obuf;
        byte[] ret = new byte[obufcount];
        System.arraycopy(obuf, 0, ret, 0, obufcount);
        return ret;
    }
    
    /**
     * Decode the base64 data.
     * @param data The base64 encoded data to be decoded
     * @param off The offset within the encoded data at which to start decoding
     * @param len The length of data to decode
     * @param ostream The OutputStream to which the decoded data should be
     *                written
     */
    public static void decode(char[] data, int off, int len,
            OutputStream ostream) throws IOException
    {
        char[] ibuf = new char[4];
        int ibufcount = 0;
        byte[] obuf = new byte[3];
        for (int i = off; i < off + len; i++)
        {
            char ch = data[i];
            if (ch == S_BASE64PAD || ch < S_DECODETABLE.length
                    && S_DECODETABLE[ch] != Byte.MAX_VALUE)
            {
                ibuf[ibufcount++] = ch;
                if (ibufcount == ibuf.length)
                {
                    ibufcount = 0;
                    int obufcount = decode0(ibuf, obuf, 0);
                    ostream.write(obuf, 0, obufcount);
                }
            }
        }
    }
    
    /**
     * Decode the base64 data.
     * @param data The base64 encoded data to be decoded
     * @param ostream The OutputStream to which the decoded data should be
     *                written
     */
    public static void decode(String data, OutputStream ostream)
            throws IOException
    {
        char[] ibuf = new char[4];
        int ibufcount = 0;
        byte[] obuf = new byte[3];
        for (int i = 0; i < data.length(); i++)
        {
            char ch = data.charAt(i);
            if (ch == S_BASE64PAD || ch < S_DECODETABLE.length
                    && S_DECODETABLE[ch] != Byte.MAX_VALUE)
            {
                ibuf[ibufcount++] = ch;
                if (ibufcount == ibuf.length)
                {
                    ibufcount = 0;
                    int obufcount = decode0(ibuf, obuf, 0);
                    ostream.write(obuf, 0, obufcount);
                }
            }
        }
    }
    
    /**
     * Returns base64 representation of specified byte array.
     * @param data The data to be encoded
     * @return The base64 encoded data
     */
    public static String encode(byte[] data)
    {
        return encode(data, 0, data.length);
    }
    
    /**
     * Returns base64 representation of specified byte array.
     * @param data The data to be encoded
     * @param off The offset within the data at which to start encoding
     * @param len The length of the data to encode
     * @return The base64 encoded data
     */
    public static String encode(byte[] data, int off, int len)
    {
        if (len <= 0)
            return "";
        char[] out = new char[len / 3 * 4 + 4];
        int rindex = off;
        int windex = 0;
        int rest = len;
        while (rest >= 3)
        {
            int i = ((data[rindex] & 0xff) << 16)
                    + ((data[rindex + 1] & 0xff) << 8)
                    + (data[rindex + 2] & 0xff);
            out[windex++] = S_BASE64CHAR[i >> 18];
            out[windex++] = S_BASE64CHAR[(i >> 12) & 0x3f];
            out[windex++] = S_BASE64CHAR[(i >> 6) & 0x3f];
            out[windex++] = S_BASE64CHAR[i & 0x3f];
            rindex += 3;
            rest -= 3;
        }
        if (rest == 1)
        {
            int i = data[rindex] & 0xff;
            out[windex++] = S_BASE64CHAR[i >> 2];
            out[windex++] = S_BASE64CHAR[(i << 4) & 0x3f];
            out[windex++] = S_BASE64PAD;
            out[windex++] = S_BASE64PAD;
        }
        else if (rest == 2)
        {
            int i = ((data[rindex] & 0xff) << 8) + (data[rindex + 1] & 0xff);
            out[windex++] = S_BASE64CHAR[i >> 10];
            out[windex++] = S_BASE64CHAR[(i >> 4) & 0x3f];
            out[windex++] = S_BASE64CHAR[(i << 2) & 0x3f];
            out[windex++] = S_BASE64PAD;
        }
        return new String(out, 0, windex);
    }
    
    /**
     * Outputs base64 representation of the specified byte array to a byte stream.
     * @param data The data to be encoded
     * @param off The offset within the data at which to start encoding
     * @param len The length of the data to encode
     * @param ostream The OutputStream to which the encoded data should be
     *                written
     */
    public static void encode(byte[] data, int off, int len,
            OutputStream ostream) throws IOException
    {
        if (len <= 0)
            return;
        byte[] out = new byte[4];
        int rindex = off;
        int rest = len;
        while (rest >= 3)
        {
            int i = ((data[rindex] & 0xff) << 16)
                    + ((data[rindex + 1] & 0xff) << 8)
                    + (data[rindex + 2] & 0xff);
            out[0] = (byte) S_BASE64CHAR[i >> 18];
            out[1] = (byte) S_BASE64CHAR[(i >> 12) & 0x3f];
            out[2] = (byte) S_BASE64CHAR[(i >> 6) & 0x3f];
            out[3] = (byte) S_BASE64CHAR[i & 0x3f];
            ostream.write(out, 0, 4);
            rindex += 3;
            rest -= 3;
        }
        if (rest == 1)
        {
            int i = data[rindex] & 0xff;
            out[0] = (byte) S_BASE64CHAR[i >> 2];
            out[1] = (byte) S_BASE64CHAR[(i << 4) & 0x3f];
            out[2] = (byte) S_BASE64PAD;
            out[3] = (byte) S_BASE64PAD;
            ostream.write(out, 0, 4);
        }
        else if (rest == 2)
        {
            int i = ((data[rindex] & 0xff) << 8) + (data[rindex + 1] & 0xff);
            out[0] = (byte) S_BASE64CHAR[i >> 10];
            out[1] = (byte) S_BASE64CHAR[(i >> 4) & 0x3f];
            out[2] = (byte) S_BASE64CHAR[(i << 2) & 0x3f];
            out[3] = (byte) S_BASE64PAD;
            ostream.write(out, 0, 4);
        }
    }
    
    /**
     * Outputs base64 representation of the specified byte array to a character stream.
     * @param data The data to be encoded
     * @param off The offset within the data at which to start encoding
     * @param len The length of the data to encode
     * @param writer The Writer to which the encoded data should be
     *               written
     */
    public static void encode(byte[] data, int off, int len, Writer writer)
            throws IOException
    {
        if (len <= 0)
            return;
        char[] out = new char[4];
        int rindex = off;
        int rest = len;
        int output = 0;
        while (rest >= 3)
        {
            int i = ((data[rindex] & 0xff) << 16)
                    + ((data[rindex + 1] & 0xff) << 8)
                    + (data[rindex + 2] & 0xff);
            out[0] = S_BASE64CHAR[i >> 18];
            out[1] = S_BASE64CHAR[(i >> 12) & 0x3f];
            out[2] = S_BASE64CHAR[(i >> 6) & 0x3f];
            out[3] = S_BASE64CHAR[i & 0x3f];
            writer.write(out, 0, 4);
            rindex += 3;
            rest -= 3;
            output += 4;
            if (output % 76 == 0)
                writer.write("\n");
        }
        if (rest == 1)
        {
            int i = data[rindex] & 0xff;
            out[0] = S_BASE64CHAR[i >> 2];
            out[1] = S_BASE64CHAR[(i << 4) & 0x3f];
            out[2] = S_BASE64PAD;
            out[3] = S_BASE64PAD;
            writer.write(out, 0, 4);
        }
        else if (rest == 2)
        {
            int i = ((data[rindex] & 0xff) << 8) + (data[rindex + 1] & 0xff);
            out[0] = S_BASE64CHAR[i >> 10];
            out[1] = S_BASE64CHAR[(i >> 4) & 0x3f];
            out[2] = S_BASE64CHAR[(i << 2) & 0x3f];
            out[3] = S_BASE64PAD;
            writer.write(out, 0, 4);
        }
    }
}
